package com.example.communist_app_api.controller.web;

import com.example.communist_app_api.config.mq.NoticeTask;
import com.example.communist_app_api.db.dto.PhotoDTO;
import com.example.communist_app_api.db.dto.PhotoUserDetailDTO;
import com.example.communist_app_api.db.pojo.User;
import com.example.communist_app_api.service.PhotoService;
import com.example.communist_app_api.service.UserService;
import com.example.communist_app_api.util.JwtUtils;
import com.example.communist_app_api.util.R;
import com.example.communist_app_api.vo.uniapp.req.PhotoShowReq;
import com.example.communist_app_api.vo.web.req.DeletePhotoByWebReq;
import com.example.communist_app_api.vo.web.req.PhotoManageShowByWebReq;
import com.github.pagehelper.PageInfo;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * @author Brother Sheng Editor
 * @version 1.0
 * Create by 2023/3/21 18:02
 */
@RestController
@RequestMapping("/photo")
@Api("随手拍管理控制器")
public class PhotoController {

    @Autowired
    private UserService userService;

    @Autowired
    private PhotoService photoService;

    @Autowired
    private NoticeTask noticeTask;

    @PostMapping("/show")
    @ApiOperation("显示所有的随手拍")
    public R showAllPhoto(HttpServletRequest httpServletRequest , @RequestBody PhotoManageShowByWebReq req){
        Integer userId = getUserIdByTokenAndWeb(httpServletRequest);
        PageInfo<PhotoDTO> pageInfo = photoService.selectAllPhotoByWebCondition(req.getPageNum(),req.getPageSize(),req.getTitle(),req.getContent(),userId);
        return R.ok().put("pageInfo", pageInfo);
    }

    @PostMapping("/delete")
    @ApiOperation("web端删除随手拍")
    public R deletedPhotoByWeb(@Valid @RequestBody DeletePhotoByWebReq req, HttpServletRequest httpServletRequest){
        Integer senderId = getUserIdByTokenAndWeb(httpServletRequest);
        Integer count = photoService.deletePhotoByPhotoId(req.getPhotoId());
        String message="非常抱歉！你发布的随手怕被管理员删除！标题为："+req.getTitle();
        String noticeName = "随手拍信息";

        noticeTask.sendNotice(senderId, String.valueOf(req.getUserId()),noticeName,message);
        return count==1?R.ok("删除成功"):R.error("删除失败");
    }


    private  Integer getUserIdByTokenAndWeb(HttpServletRequest httpServletRequest) {
        String token = httpServletRequest.getHeader("token");
        Claims claims = JwtUtils.parseJWT(token);
        String username = claims.getSubject();
        User userInfo = userService.getUserInfo(username);
        return userInfo.getId();
    }
}
